<div id="formDiv"></div>
<script type="text/html" id="produceContract">
  <form lay-filter="produceContractForm" id="produceContractForm" class="layui-form open-form">
    <div class="open-model">
      <div class="open-auto">
        <div>
          <table class="layui-table">
            <thead>
            <tr>
              {{# if(d.eventName === 'detail'){ }}
              <th lay-data="{field:'materialName', width:150, sort: true, fixed: 'left'}">合同编号
              </th>
              <th lay-data="{field:'materialName', width:150, sort: true, fixed: 'left'}">合同名称
            </th>
              {{# } }}
              <th lay-data="{field:'materialName', width:150, sort: true, fixed: 'left'}">合同类型
              </th>
              <th lay-data="{field:'materialSpec', width:150, sort: true, fixed: 'left'}">客户信息仓库编号</th>
              <th lay-data="{field:'materialUnit', width:150, sort: true, fixed: 'left'}">客户级别</th>
              <th lay-data="{field:'materialSpec', width:150, sort: true, fixed: 'left'}">
                联系人
              </th>
              <th lay-data="{field:'materialSpec', width:150, sort: true, fixed: 'left'}">电话</th>
              {{# if(d.eventName !== 'detail'){ }}
              <th lay-data="{field:'materialUnit', width:150, sort: true, fixed: 'left'}">邮箱</th>
              {{# } }}
              <th lay-data="{field:'materialUnit', width:150, sort: true, fixed: 'left'}">申请日期	</th>
              {{# if(d.eventName === 'detail'){ }}
              <th lay-data="{field:'materialUnit', width:150, sort: true, fixed: 'left'}">生效日期	</th>
              <th lay-data="{field:'materialUnit', width:150, sort: true, fixed: 'left'}">有效截止日期	</th>
              {{# } }}

<!--              <th lay-data="{field:'materialUnit', width:150, sort: true, fixed: 'left'}">备注</th>-->
            </tr>
            </thead>
            <tbody>
            <tr>
              {{# if(d.eventName === 'detail'){ }}
              <td class="chooseCode">
                <input class="layui-input adv-disable" id="contractCode" disabled
                       name="contractCode"/>

              </td>
              <td class="chooseCode">
                <input class="layui-input adv-disable" id="contractName" disabled
                       name="contractName"/>

              </td>
              {{# } }}
              <td class="chooseCode">
                <input class="layui-input adv-disable" id="type" disabled
                       name="type"/>

              </td>
              <td>
              <select id="warehouseCustomerId" name="warehouseCustomerId"
                      lay-filter="warehouseCustomerId" lay-search required></select>
              </td>
              <td>
                <input type="text" class="layui-input" disabled id="customerLevelId"
                       name="customerLevelId"/>
              </td>
              {{# if(d.eventName !== 'detail'){ }}
              <td>
                <select id="contactId" name="contactId"
                        lay-filter="contactId" lay-search required></select>
              </td>
              {{# } }}
              {{# if(d.eventName === 'detail'){ }}
              <td>
                <input class="layui-input adv-disable" id="contactName" disabled
                       name="contactName"/>
              </td>
              {{# } }}
              <td>
                <input class="layui-input adv-disable" id="phone" disabled
                       name="phone"/>
              </td>
              {{# if(d.eventName !== 'detail'){ }}
              <td>
                <input class="layui-input adv-disable" id="mail" disabled
                       name="mail"/>
              </td>
              {{# } }}
              <td>
                <input class="layui-input adv-disable" id="contractTime" disabled
                       name="contractTime"/>
              </td>

              {{# if(d.eventName === 'detail'){ }}
              <td>
                <input class="layui-input adv-disable" id="effectiveDate" disabled
                       name="effectiveDate"/>
              </td>
              <td>
                <input class="layui-input adv-disable" id="expiryDate" disabled
                       name="expiryDate"/>
              </td>
              {{# } }}
            </tr>
            </tbody>
          </table>
        </div>
        {{# if(d.eventName !== 'detail'){ }}
        <div class="layui-form-item tableContent" id="processCont" style="overflow: visible;">
          <label class="layui-form-label" style="text-align: left">审核内容：</label>
          <table class="layui-table" id="processFormTable" lay-filter="processFormTable"></table>
        </div>
        {{# } }}
        <div class="layui-form-item layui-row" id="continto">
          <div style="width: calc(50% - 25px);float:left;">
            <label class="layui-form-label" style="text-align: left">服务产品价格：</label>
            <table class="layui-table" id="serviceProductsFormTable"
                   lay-filter="serviceProductsFormTable"></table>
          </div>
          <div style="margin-left: 50px;float: right;width: calc(50% - 25px);">
            <label class="layui-form-label" style="text-align: left">加工费单价设置：</label>
            <table class="layui-table" id="custodyFeesFormTable"
                   lay-filter="custodyFeesFormTable"></table>
          </div>
        </div>
        <div class="layui-form-item text-right">
          <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">关闭</button>
          <button class="layui-btn" lay-filter="formSubmit" type="button" lay-submit>提交</button>
        </div>
      </div>
    </div>
  </form>
</script>


<script>
  layui.use(["layer", "form", "table", "admin", "laydate", "upload", "laytpl"], async function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var form = layui.form;
    var table = layui.table;
    var config = layui.config;
    var admin = layui.admin;
    var upload = layui.upload;
    let laydate = layui.laydate;
    let laytpl = layui.laytpl;
    const nowData = {...parentData};

    let data = nowData?.data;

    try {
      if (!data.status) {
        nowData.status = 0
      } else {
        nowData.status = data.status
      }
    } catch (e) {
      nowData.status = 0
    }


    laytpl(produceContract.innerHTML).render({...nowData}, function (html) {
      $("#formDiv").after(html);
    });
    var stamp= new Date().getTime() + 8 * 60 * 60 * 1000;
    var beijingTime = new Date(stamp).toISOString().replace(/T/, '').replace(/:/g, '').replace(/\..+/, '').substring(0, 10);
    $("#type").val('生产合同')
    $("#contractTime").val(beijingTime)


    const receiptType = await admin.reqPro('enterprise/contract/admin/contractCategory/list?page=1&limit=9999', {});
    const receiptTypeList = receiptType.data

    const customersInfo = await admin.reqPro('enterprise/sell/admin/customersInfo/list', {});
    const customersList = customersInfo.data
    var warehouseUserList = [];

    const contractorcont = await admin.reqPro('user/admin/user/list?limit=9999', {});
    const contractorList = contractorcont.data;

    await admin.initDataSelectPro(
            "enterprise/sell/admin/customersInfo/list",
            {limit: 99999},
            "warehouseCustomerId",
            "客户编号",
            async (d, obj) => {
              var item = {
                  type: '生产合同',
                  customerLevelId:1,
                  contactId: "",
                  phone: "",
                  mail: "",
                  remark: "",
              }
              form.val("produceContractForm", item);

              if (obj) {

              }
              if (d.value) {
                form.val('produceContractForm', {
                  customerId:d.value,
                })
                let warehouseUser=await admin.reqPro("enterprise/sell/admin/contactInfo/list?page=1&limit=9999", {selCustomerId: d.value})
                let allTableCont=table.cache["processFormTable"];
                allTableCont.map(i=>{i.warehouseUserList=warehouseUser.data;i.contractName=item.type+obj.customerName+today.getFullYear()})
                table.reload("processFormTable",{data:allTableCont});
                userNameSelect(d.value);
              } else {
              }

            },
            "customerName"
    );


    async function userNameSelect(id){
      await admin.initDataSelectPro(
              "enterprise/sell/admin/contactInfo/list?page=1&limit=9999",
              {selCustomerId: id},
              "contactId",
              "联系人",
              async (d, obj) => {
                if (obj) {

                }
                if (d.value) {
                  form.val('produceContractForm', {
                    warehouseUserId:obj.id,
                    phone:obj.telephone,
                    mail:obj.email,
                  })
                }
              },
              "name"
      );
    }

    const processFormVal = table.render({
      elem: "#processFormTable",
      page: false,
      limit: 999999,
      data: [],
      cols: [
        [
          // {
          //   field: "type", align: "center", title: "合同类型",
          // },
          {
            field: "contractCode", align: "center", title: "合同编号",
            templet: admin.setTableInput("contractCode", nowData.eventName == "detail", "contractCode")
          },
          {
            field: "contractName",
            align: "center",
            title: "合同名称",
            templet: admin.setTableInput("contractName", nowData.eventName == "detail", "contractName")
          },
          {
            field: "contractCategoryId",
            align: "center",
            title: "合同分类",
            templet: admin.setTableSelect("contractCategoryId",
                    receiptTypeList.map((v) => {
                      return {
                        label: v.name,
                        value: v.id
                      };
                    }), nowData.eventName === "detail", "contractCategoryId")
          },
          {
            field: "warehouseUserId", align: "center", title: "客户签约人",
            templet: function (d) {
              if(d.warehouseUserName!==''){
                return d.warehouseUserName
              }else{
                if (d.warehouseUserList) {
                  return admin.setTableSelect(
                          "warehouseUserId",
                          d.warehouseUserList.map((v) => {
                            return {
                              label: v.name,
                              value: v.id
                            };
                          }),
                          nowData.eventName === "detail",
                          "warehouseUserId"
                  )(d);
                }else{
                  return ''
                }
              }
            }
          },
          {
            field: "contractorId", align: "center", title: "我方签约人",
            templet: admin.setTableSelect("contractorId", contractorList.map((v) => {
              return {
                label: v.nickname,
                value: v.id
              };
            }), nowData.eventName === "detail", "contractorId")
          },
          {
            field: "contractFileUrl", align: "center", title: "合同附件",
            templet: admin.setTableUpload("contractFileUrl", nowData.eventName == "detail")
          },
          {
            field: "effectiveDate", align: "center", title: "生效日期",
            templet: admin.setTableInput('effectiveDate', nowData.eventName === 'recList', 'effectiveDate'),
          },
          {
            field: "expiryDate", align: "center", title: "有效截止日期",
            templet: admin.setTableInput('expiryDate', nowData.eventName === 'recList', 'expiryDate'),
          },
          {
            field: "remark", align: "center", title: "备注信息",
            templet: admin.setTableInput("remark", nowData.eventName == "detail", "remark")
          },
        ]
      ],
      done: function () {
        admin.tableInputChange("processFormTable");
        admin.tableSelectChange("processFormTable", 'contractCategoryId');
        admin.tableSelectChange("processFormTable", 'warehouseUserId');
        admin.tableSelectChange("processFormTable", 'contractorId');
        // 上传图片
        upload.render({
          elem: ".upload-btn", // 绑定上传按钮
          url: config.upload_url + "uploadFile",
          accept: "file", // 可接受的文件类型
          headers: {Authorization: "Bearer " + config.getToken()},
          done: function (res, index, upload) {
            // 上传成功的回调
            if (res.code === 200) {
              // 更新表格缓存中的数据
              const button = $(this.item);
              const index = button.data("index");
              let tableData = table.cache["processFormTable"];
              let rowIndex = tableData.findIndex((v) => v["LAY_TABLE_INDEX"] == index);
              if (rowIndex > -1) {
                tableData[rowIndex].contractFileUrl = res.data.url; // 假设接口返回的文件路径是 res.data.fileUrl
                tableData[rowIndex].contractFileUrlName = res.data.fileName; // 假设接口返回的文件路径是 res.data.fileUrl
              }
              $(`#uploaded-${index}`).html(`<a href="${res.data.url}" target="_blank">查看附件</a>`);
              console.log("文件上传成功:", res.data);
            } else {
              console.error("文件上传失败:", res.message);
            }
          },
          error: function () {
            // 上传失败的回调
            console.error("上传失败");
          }
        });
        const expiryDate = document.querySelectorAll('.expiryDate');
        expiryDate.forEach((input, index) => {
          laydate.render({
            elem: input,
            format: 'yyyy-MM-dd HH:mm:ss',
            trigger: 'click',
            done: function (value) {
              input.value = value;
              let tableData = table.cache['processFormTable'];
              let rowIndex = tableData.findIndex((v) => v['LAY_TABLE_INDEX'] == index);
              if (rowIndex > -1) {
                tableData[rowIndex].expiryDate = value;
              }
            },
          });
        });
        const effectiveDate = document.querySelectorAll('.effectiveDate');
        effectiveDate.forEach((input, index) => {
          laydate.render({
            elem: input,
            format: 'yyyy-MM-dd HH:mm:ss',
            trigger: 'click',
            done: function (value) {
              input.value = value;
              let tableData = table.cache['processFormTable'];
              let rowIndex = tableData.findIndex((v) => v['LAY_TABLE_INDEX'] == index);
              if (rowIndex > -1) {
                tableData[rowIndex].effectiveDate = value;
              }
            },
          });
        });
      }
    });
    var beijingTime2 = new Date(stamp).toISOString().replace(/T/, '').replace(/-/g, '').replace(/:/g, '').replace(/\..+/, '').substring(0, 12);
    var today = new Date();
    var cot = [{
      contractCode: beijingTime2,
      contractName: "",
      contractCategoryId: "",
      warehouseUserName:"",
      warehouseUserId: "",
      warehouseUserList:[],
      contractorId: "",
      contractFileUrl: "",
      effectiveDate: "",
      expiryDate: "",
      remark: ""
    }]

    table.reload("processFormTable", {
      data: cot
    });



    /*服务产品价格*/
    let tableVal = table.render({
      elem: "#serviceProductsFormTable",
      // page: false,
      limit: 9999,
      height: 350,
      // url: config.base + 'warehouse/warehouse/feeItems/list',
      data: [],
      cols: [
        [
          {field: "feeItemName", align: "center", title: "业务项目"},
          {field: "remark", align: "center", title: "业务描述"},
          {field: "price", align: "center", title: "标准价"},
          {field: "memberPrice", align: "center", title: "会员价"},
          {
            field: "contractPrice", align: "center", title: "合同价格",
            templet: admin.setTableInput("contractPrice", nowData.eventName === "detail", "contractPrice")
          },
        ]
      ],
      done: function (res, curr, count) {
        admin.tableInputChangeByClass("serviceProductsFormTable", "contractPrice");
      },
      parseData: function (res) {
      },
    });

    /*托管费用设置*/
    const VarietyVal = table.render({
      elem: "#custodyFeesFormTable",
      page: false,
      limit: 9999,
      height: 350,
      data: [],
      cols: [
        [
          {field: "markName", align: "center", title: "业务项目"},
          {field: "warehouseContractPrice", align: "center", title: "标准价"},
          {field: "memberPrice", align: "center", title: "会员价"},
          {
            field: "newContractPrice", align: "center", title: "合同价格",
            templet: admin.setTableInput("newContractPrice", nowData.eventName === "detail", "newContractPrice")
          },
        ]
      ],
      done: function () {
        admin.tableInputChangeByClass("custodyFeesFormTable", "newContractPrice");
      },
      parseData: function (res) {

      },
    });
    console.log(nowData,"nowData")
    if (nowData.eventName === "detail") {
      $("#continto").show();
      $("#produceContractForm .layui-table-cell").css("overflow", "hidden ");
      admin.setFormDisable("#produceContractForm", true);
    } else {
      const feeItemsList = await admin.reqPro('warehouse/warehouse/feeItems/list', {});
      const VarietyList = await admin.reqPro('warehouse/warehouse/admin/productMark/list', {});
      feeItemsList.data.map(item => {
        if (item.price === '' || item.price === undefined) {
          item.contractPrice = item.price = 0
        } else if (item.price === 0) {
          item.contractPrice = '0'
        } else if (item.price !== 0 && item.price !== '') {
          item.contractPrice = item.price
        }
        item.memberPrice = 0
      })
      VarietyList.data.map(item => {
        item.warehouseContractPrice = item.contractPrice
        if (item.contractPrice === '' || item.contractPrice === undefined) {
          item.newContractPrice = item.contractPrice = 0
        } else if (item.contractPrice === 0) {
          item.newContractPrice = '0'
        } else if (item.contractPrice !== 0 && item.contractPrice !== '') {
          item.newContractPrice = item.contractPrice
        }
      })
      const feeItemsCont = feeItemsList.data
      const VarietyCont = VarietyList.data
      tableVal.reload({
        data: feeItemsCont
      });
      VarietyVal.reload({
        data: VarietyCont
      });
    }
    if (data && data.id) {
      data.warehouseCustomerId=data.customerId
      data.phone=data.telephone
      data.type='生产合同'
      data.customerLevelId='1'
      data.contractTime=data.createTime
      form.val("produceContractForm",data);
      $("#contactId").val(data.contactName)
      if (data.warehouseContractFeeVOList != undefined) {
        tableVal.reload({
          data: data.warehouseContractFeeVOList.map(v => {
            delete v.length
            return v
          }),
        });
      }
      if (data.warehouseContractProductVOList != undefined) {
        VarietyVal.reload({
          data: data.warehouseContractProductVOList.map(v => {
            v.newContractPrice = v.contractPrice
            v.markName = v.varietyName
            delete v.length
            return v
          })
        });
      }


    } else {
      console.log(111111)

    }
    console.log(data, "-----data-------data")
    form.on("submit(formSubmit)", function (d) {
      let formData = {}
      let formCont={...d.field}
      let processForm = table.cache["processFormTable"];
      formData = { ...d.field, ...processForm[0]};
      formData.type = 3
      formData.warehouseFeeItemsList = table.cache["serviceProductsFormTable"]
      formData.warehouseProductVarietyList = table.cache["custodyFeesFormTable"]
      formData.warehouseFeeItemsList.map(item => {
        item.price = item.contractPrice
      })
      formData.warehouseProductVarietyList.map(item => {
        item.contractPrice = Number(item.newContractPrice)
      })
      if (formData.warehouseCustomerId === '') {
        layer.msg("请选择客户", {icon: 2, time: 1000});
        return false;
      }
      if (formData.contactId === '') {
        layer.msg("请选择联系人", {icon: 2, time: 1000});
        return false;
      }
      if (formData.contractCode === '') {
        layer.msg("请填写合同编号", {icon: 2, time: 1000});
        return false;
      }
      if (formData.contractName === '') {
        layer.msg("请填写合同名称", {icon: 2, time: 1000});
        return false;
      }
      if (formData.contractCategoryId === '') {
        layer.msg("请选择合同分类", {icon: 2, time: 1000});
        return false;
      }
      if (formData.warehouseUserId === '') {
        layer.msg("请选择客户签约人", {icon: 2, time: 1000});
        return false;
      }
      if (formData.contractorId === '') {
        layer.msg("请选择我方签约人", {icon: 2, time: 1000});
        return false;
      }
      if (formData.effectiveDate === '') {
        layer.msg("请选择合同生效日期", {icon: 2, time: 1000});
        return false;
      }
      if (formData.expiryDate === '') {
        layer.msg("请选择合同有效截止日期", {icon: 2, time: 1000});
        return false;
      }
      if (formData.warehouseFeeItemsList.some(item => item.price === ''  || Number(item.price) < 0)) {
        layer.msg("请填写服务产品合同价格", {icon: 2, time: 1000});
        return false;
      }

      if (formData.warehouseProductVarietyList.some(item => item.contractPrice === ''  || Number(item.contractPrice) < 0)) {
        layer.msg("请填写托管费用合同价格", {icon: 2, time: 1000});
        return false;
      }
      admin.req(
              "warehouse/warehouse/produceContract/add",
              JSON.stringify(formData),
              function (res) {
                layer.closeAll("loading");
                if (res.code == 200) {
                  layer.msg(res.msg, {icon: 1});
                  table.reload('warehouseContractTable');
                  layer.closeAll("page");
                } else {
                  layer.msg(res.msg, {icon: 2, time: 1000});
                }
              },
              "POST",
              false,
              "application/json"
      );
    });

    $("#produceContractForm .layui-table-body").css("overflow", "visible");
    $("#produceContractForm .layui-table-box").css("overflow", "visible");
    $("#produceContractForm .layui-table-view").css("overflow", "visible");
  });
</script>

<style>

  #produceContractForm .layui-form-label {
    width: 125px;
  }

  #produceContractForm .layui-input-block {
    margin-left: 155px;
  }

  #produceContractForm .layui-form-item .layui-inline {
    /* margin-bottom: 5px; */
    margin-right: 0px;
  }

  #produceContractForm .layui-table-cell {
    overflow: visible;
  }

  #produceContractForm .layui-table-box {
    overflow: visible !important;
  }

  #produceContractForm .layui-table-body {
    overflow: visible !important;
  }

  #continto .layui-table-box {
    overflow: hidden !important;
  }

  #continto .layui-table-body {
    overflow: auto !important;
  }

  .chooseCode {
    position: relative;
  }

  .mask {
    position: absolute;
    width: 100%;
    height: 100%;
    background: rgba(158, 157, 157, 0.1);
    top: 50%;
    left: 50%;
    z-index: 2;
    transform: translate(-50%, -50%);
  }

</style>